package com.twotiger.and.util;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

import com.hyphenate.EMCallBack;
import com.hyphenate.EMError;
import com.hyphenate.chat.EMClient;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.exceptions.HyphenateException;
import com.twotiger.and.activity.base.BaseActivity;
import com.twotiger.and.activity.others.ChatActivity;

public class EaseHXUtils {

    private Dialog loadingDialog;

    /**
     * 登陆环信服务器，并进入环信聊天界面。 如果第一次，则创建一个随机用户。  
     * 
     * @param context
     */
    public void startEaseChat(Context context) {

        if (EMClient.getInstance().isLoggedInBefore()) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        //加载本地数据库中的消息到内存中
                        EMClient.getInstance().groupManager().loadAllGroups();
                        EMClient.getInstance().chatManager().loadAllConversations();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();
            context.startActivity(new Intent(context, ChatActivity.class).putExtra(
                EaseConstant.EXTRA_USER_ID, "kefuzhuanyong"));
        } else {
            //随机创建一个用户并登录环信服务器
            createRandomAccountAndLoginChatServer(context);
        }
    }

    protected void createRandomAccountAndLoginChatServer(final Context context) {
        loadingDialog = PromptManager.showLoadDataDialog(context, "正在加载...");
        // 自动生成账号
        final String randomAccount = RandomUtils.getRandomNumbersAndLetters(10);
        final String userPwd = "123456";
        createAccountToServer(randomAccount, userPwd, new EMCallBack() {

            @Override
            public void onSuccess() {
                ((Activity)context).runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        //登录环信服务器
                        loginHuanxinServer(context, randomAccount, userPwd);
                    }
                });
            }

            @Override
            public void onProgress(int progress, String status) {
            }

            @Override
            public void onError(final int errorCode, final String message) {
                PromptManager.closeLoadDataDialog(loadingDialog);
                ((Activity)context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (errorCode == EMError.NETWORK_ERROR) {
                            ((BaseActivity)context).showToast("网络不可用");
                        } else if (errorCode == EMError.USER_ALREADY_EXIST) {
                            loginHuanxinServer(context, randomAccount, userPwd);
                        } else if (errorCode == EMError.INVALID_USER_NAME) {
                            ((BaseActivity)context).showToast("用户名非法");
                        } else {
                            ((BaseActivity)context).showToast("注册失败");
                        }
                    }
                });
            }
        });
    }

    //注册用户
    private void createAccountToServer(final String uname, final String pwd,
                                       final EMCallBack callback) {
        Thread thread = new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    EMClient.getInstance().createAccount(uname, pwd);
                    if (callback != null) {
                        callback.onSuccess();
                    }
                } catch (HyphenateException e) {
                    if (callback != null) {
                        callback.onError(e.getErrorCode(), e.getMessage());
                    }
                }

            }
        });
        thread.start();
    }
    
    private void loginHuanxinServer(final Context context, final String uname, final String upwd) {
        EMClient.getInstance().login(uname, upwd, new EMCallBack() {
            @Override
            public void onSuccess() {
                PromptManager.closeLoadDataDialog(loadingDialog);
                ((Activity)context).runOnUiThread(new Runnable() {
                    public void run() {
                        EMClient.getInstance().groupManager().loadAllGroups();
                        EMClient.getInstance().chatManager().loadAllConversations();
                    }
                });
                context.startActivity(new Intent(context, ChatActivity.class).putExtra(
                    EaseConstant.EXTRA_USER_ID, "kefuzhuanyong"));
            }

            @Override
            public void onProgress(int progress, String status) {
            }

            @Override
            public void onError(final int code, final String message) {
                PromptManager.closeLoadDataDialog(loadingDialog);
                ((Activity)context).runOnUiThread(new Runnable() {
                    public void run() {
                        Toast.makeText(context, "登陆失败:" + message, Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }

}
